package com.powernode.queryops;

import com.powernode.commons.util.ReleaseResourceUtils;

import java.sql.*;
import java.util.ResourceBundle;

/**
 * @Author Arrebol
 * @Date 2024/8/1 14:35
 * @Project jdbc
 * @Description： 获取新增行的主键值
 */
public class JdbcTest4 {
    public static void main(String[] args) {
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
        String driver = bundle.getString("driver");
        String url = bundle.getString("url");
        String user = bundle.getString("user");
        String password = bundle.getString("password");

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, user, password);
            stmt = conn.createStatement();
            String sql1 = "insert into t_product (name, price, create_time) " +
                    "values ('小米su7',1.0,'2024/08/01')";
            //第二个参数为标志位，表示是否将新插入数据行的主键值返回
            int count = stmt.executeUpdate(sql1, Statement.RETURN_GENERATED_KEYS);
            System.out.println("插入了" + count + "条记录");
            //获取新增行的主键值
            //返回的结果集中就包含了新增行的主键值
            rs = stmt.getGeneratedKeys();
            //通过结果集取主键值
            if(rs.next()){
                long id = rs.getLong(1);
                System.out.println("新增行的主键值为："+id);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ReleaseResourceUtils.release(rs, stmt, conn);
        }
    }
}
